import Vue from "vue";
import messageBox from './index.vue'

const MessageBoxConstructor = Vue.extend(messageBox);
let instance;
const initInstance = function (options) {
  instance = new MessageBoxConstructor({
    el: document.createElement('div'),
    data: options
  });
}

const destroyInstance = function () {
  if (instance && instance.$el) {
    document.body.removeChild(instance.$el);
    instance = null;
  }
};
const cMessageBox = (options) => {
  return new Promise((resolve, reject) => {
    initInstance(options)
    instance.resolve = resolve;
    instance.reject = reject;
    instance.$on('close', () => {
      destroyInstance()
    })
    document.body.appendChild(instance.$el);
    Vue.nextTick(() => {
      instance.visible = true
    })
  })
}
cMessageBox.confirm = (message, title = '提示', options) => {
  return cMessageBox({
    title,
    message,
    showCancelBtn: true,
    ...options
  })
}
cMessageBox.alert = (message, title = '提示', options) => {
  return cMessageBox({
    title,
    message,
    showCancelBtn: false,
    ...options
  })
}
cMessageBox.install = function (Vue) {
  Vue.prototype.$cMessageBox = cMessageBox
}
export default cMessageBox
